package com.miot.domain.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.miot.object.scene.PackageSceneVo;
import org.apache.http.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhangyanbin
 * @Date: 2019/1/27 18:17
 * @Version 1.0
 */
public class MISceneUtil {
    protected static Logger logger = LoggerFactory.getLogger(MISceneUtil.class);

    /**
     * 创建场景 POST
     */
    public static final String MI_CREATE_SENCE = "/bridge/s2s/scene/create";
    /**
     * 编辑场景 POST
     */
    public static final String MI_EDIT_SENCE = "/bridge/s2s/scene/edit";
    /**
     * 删除场景 POST
     */
    public static final String MI_DELETE_SENCE = "/bridge/s2s/scene/delete";
    /**
     * 获取场景列表 GET
     */
    public static final String MI_GET_SENCE_LIST = "/bridge/s2s/scene/getlist";

    /**
     * 获取设备支持的操作列表 GET
     */
    public static final String MI_GET_TPL_LIST = "/bridge/s2s/scene/gettpllist";

    /**
     * 获取场景信息 GET
     */
    public static final String MI_SCENE_INFO = "/bridge/s2s/scene/sceneinfo";
    /**
     * 获取场景运行log GET
     */
    public static final String MI_SCENE_RUN_LOG = "/bridge/s2s/scene/runlog";
    /**
     * 清除场景log POST
     */
    public static final String MI_SCENE_CLEAN_LOG = "/bridge/s2s/scene/cleanlog";

    /**
     * 创建/修改场景接口
     *
     * @param controlUnitId 要创建场景的UnitId
     * @param stId          场景模板ID
     * @param usId          场景ID
     * @param name          场景名字
     * @param identify      某些情况可以填did，暂时不用
     * @param packageSceneVo 场景相关的设置
     * @param authed        场景相关的did列表
     * @return
     */
    public static JSONObject createOrUpdate(long controlUnitId, long stId, long usId, String name, String identify, PackageSceneVo packageSceneVo, String authed, String method) {
        try {
            List<NameValuePair> params = new ArrayList<>();
            String url = null;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("st_id", stId);
            dataValueJson.put("name", name);
            dataValueJson.put("identify", identify);
            dataValueJson.put("setting", new Gson().toJson(packageSceneVo));
            dataValueJson.put("authed", authed);
            dataValueJson.put("accessKey", "your_mipush_id");
            if (method.equalsIgnoreCase(ControlUnitUtil.EDIT_METHOD)) {
                dataValueJson.put("us_id", usId);
                url = ControlUnitUtil.URI + MISceneUtil.MI_EDIT_SENCE;
                params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MISceneUtil.MI_EDIT_SENCE, dataValueJson.toString());
            } else {
                url = ControlUnitUtil.URI + MISceneUtil.MI_CREATE_SENCE;
                params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MISceneUtil.MI_CREATE_SENCE, dataValueJson.toString());

            }
            System.err.println(params);
            logger.info("参数={}",params);
            String postResult = HttpUtils.sendPost(url, params);
            JSONObject resultJSON = JSONObject.parseObject(postResult);
            if (StringUtils.pathEquals("ok", resultJSON.getString("result"))) {
                String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("result");
                return JSONObject.parseObject(responseBody);
            } else {
                logger.error("小米接口->创建/修改场景接口={}", resultJSON);
                return new JSONObject();
            }
        } catch (Exception e) {
            logger.error("小米接口->创建/修改场景错误信息={}", e.getMessage());
        }
        return new JSONObject();
    }

    /**
     * 删除场景接口
     *
     * @param controlUnitId 要创建场景的UnitId
     * @param usId          场景ID
     * @return
     */
    public static Boolean deleteScene(long controlUnitId, long usId) {
        try {
            String url = ControlUnitUtil.URI + MISceneUtil.MI_DELETE_SENCE;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("us_id", usId);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MISceneUtil.MI_DELETE_SENCE, dataValueJson.toString());
            String postResult = HttpUtils.sendPost(url, params);
            JSONObject resultJSON = JSONObject.parseObject(postResult);
            if (StringUtils.pathEquals("ok", resultJSON.getString("result"))) {
                JSONObject.parseObject(postResult).getJSONObject("data").getString("result");
                return true;
            }
        } catch (Exception e) {
            logger.error("小米接口->删除场景接口错误信息={}", e.getMessage());
        }
        return false;
    }

    /**
     * 获取场景列表
     *
     * @param controlUnitId 要创建场景的UnitId
     * @param stId          场景模板ID
     * @param realDid       设备did(需要调用开放平台接口获取真正的did)
     * @param identify      某些情况可以填did，暂时不用
     * @param start         从第几个开始
     * @param limit         最多返回多少个
     * @return
     */
    public static JSONArray getSceneList(long controlUnitId, long stId, String realDid, String identify, Long start, Long limit) {
        try {
            String url = ControlUnitUtil.URI + MISceneUtil.MI_GET_SENCE_LIST;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("st_id", stId);
            dataValueJson.put("did", realDid);
            dataValueJson.put("identify", identify);
            dataValueJson.put("start", 1);
            dataValueJson.put("limit", 100);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.GET_METHOD, MISceneUtil.MI_GET_SENCE_LIST, dataValueJson.toString());
            System.err.println(params);
            String postResult = HttpUtils.sendGet(url, params,null);
            JSONObject resultJSON = JSONObject.parseObject(postResult);
            if (StringUtils.pathEquals("ok", resultJSON.getString("result"))) {
                JSONArray responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getJSONArray("result");
                return responseBody;
            } else {
                logger.error("小米接口->获取场景列表接口={}", resultJSON);
                return new JSONArray();
            }
        } catch (Exception e) {
            logger.error("小米接口->获取场景列表错误信息={}", e.getMessage());
        }
        return new JSONArray();
    }

    /**
     * 获取设备支持的操作列表
     *
     * @param controlUnitId 要创建场景的UnitId
     * @param realDid       场景模板ID
     * @return
     */
    public static JSONObject getSceneTplList(long controlUnitId, String realDid) {
        try {
            String url = ControlUnitUtil.URI + MISceneUtil.MI_GET_TPL_LIST;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("did", realDid);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.GET_METHOD, MISceneUtil.MI_GET_TPL_LIST, dataValueJson.toString());
            String postResult = HttpUtils.sendGet(url, params, null);
            JSONObject resultJSON = JSONObject.parseObject(postResult);
            if (StringUtils.pathEquals("ok", resultJSON.getString("result"))) {
                String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("result");
                return JSONObject.parseObject(responseBody);
            } else {
                logger.error("小米接口->获取场景列表接口信息={}", resultJSON);
                return new JSONObject();
            }
        } catch (Exception e) {
            logger.error("小米接口->获取场景列表接口错误信息={}", e.getMessage());
        }
        return new JSONObject();
    }

    /**
     * 获取场景信息
     *
     * @param controlUnitId
     * @param usId
     * @return
     */
    public static JSONObject getSceneInfo(Long controlUnitId, Long usId) {
        try {
            String url = ControlUnitUtil.URI + MISceneUtil.MI_SCENE_INFO;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("us_id", usId);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.GET_METHOD, MISceneUtil.MI_SCENE_INFO, dataValueJson.toString());
            String postResult = HttpUtils.sendGet(url, params, null);
            JSONObject resultJSON = JSONObject.parseObject(postResult);
            if (StringUtils.pathEquals("ok", resultJSON.getString("result"))) {
                String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("result");
                return JSONObject.parseObject(responseBody);
            } else {
                logger.error("小米接口->获取场景信息接口信息={}", resultJSON);
                return new JSONObject();
            }
        } catch (Exception e) {
            logger.error("小米接口->获取场景信息接口错误信息={}", e.getMessage());
        }
        return new JSONObject();
    }

    /**
     * 获取场景日志
     *
     * @param controlUnitId 要创建场景的UnitId
     * @param timestamp     时间戳
     * @return
     */
    public static JSONObject getRunLog(Long controlUnitId, Long timestamp) {
        try {
            String url = ControlUnitUtil.URI + MISceneUtil.MI_SCENE_RUN_LOG;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            dataValueJson.put("timestamp", timestamp);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.GET_METHOD, MISceneUtil.MI_SCENE_RUN_LOG, dataValueJson.toString());
            String postResult = HttpUtils.sendGet(url, params, null);
            JSONObject resultJSON = JSONObject.parseObject(postResult);
            if (StringUtils.pathEquals("ok", resultJSON.getString("result"))) {
                String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("result");
                return JSONObject.parseObject(responseBody);
            } else {
                logger.error("小米接口->获取场景列表接口信息={}", resultJSON);
                return new JSONObject();
            }
        } catch (Exception e) {
            logger.error("小米接口->获取场景列表接口错误信息={}", e.getMessage());
        }
        return new JSONObject();
    }
    /**
     * 清除场景日志
     *
     * @param controlUnitId 要创建场景的UnitId
     * @return
     */
    public static JSONObject cleanLog(Long controlUnitId) {
        try {
            String url = ControlUnitUtil.URI + MISceneUtil.MI_SCENE_CLEAN_LOG;
            JSONObject dataValueJson = new JSONObject();
            dataValueJson.put("controlUnitId", controlUnitId);
            List<NameValuePair> params = ControlUnitUtil.createParams(ControlUnitUtil.POST_METHOD, MISceneUtil.MI_SCENE_CLEAN_LOG, dataValueJson.toString());
            String postResult = HttpUtils.sendPost(url, params);
            JSONObject resultJSON = JSONObject.parseObject(postResult);
            if (StringUtils.pathEquals("ok", resultJSON.getString("result"))) {
                String responseBody = JSONObject.parseObject(postResult).getJSONObject("data").getString("result");
                return JSONObject.parseObject(responseBody);
            } else {
                logger.error("小米接口->清除场景日志接口信息={}", resultJSON);
                return new JSONObject();
            }
        } catch (Exception e) {
            logger.error("小米接口->清除场景日志接口错误信息={}", e.getMessage());
        }
        return new JSONObject();
    }
}
